import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Request,
  Put,
  Query,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { UserAdminService } from './user-admin.service';
import { UpdateUserDto } from './dto/update-user-admin.dto';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { CreateUserDto } from './dto/create-user-admin.dto';
import { UserQueryDto } from './dto/query-user-admin.dto';
import { LoginDto } from './dto/login-user-admin.dto';
import { Public } from 'src/common/decorators/public';
@ApiTags('admin-用户管理')
@Controller('user-admin')
export class UserAdminController {
  constructor(private readonly userAdminService: UserAdminService) {}

  // 验证相关接口
  @Post('login')
  @Public()
  @ApiOperation({ summary: '用户登录' })
  login(@Body() loginDto: LoginDto) {
    return this.userAdminService.login(loginDto);
  }

  @Get('captcha')
  @Public()
  @ApiOperation({ summary: '获取验证码' })
  async getCaptcha() {
    const captchaData = await this.userAdminService.generateCaptcha();
    return captchaData;
  }

  @Post('logout')
  @ApiOperation({ summary: '用户退出登录' })
  async logout(@Request() request) {
    // 获取当前用户ID和令牌
    const userId = request.user?.id;

    if (!userId) {
      throw new HttpException('未登录', HttpStatus.UNAUTHORIZED);
    }

    // 从请求头中获取token
    const authHeader = request.headers.authorization;
    if (!authHeader) {
      throw new HttpException('未提供token', HttpStatus.BAD_REQUEST);
    }

    const token = authHeader.replace('Bearer ', '');
    const result = await this.userAdminService.logout(userId, token);

    if (result) {
      return { code: 200, message: '退出成功' };
    } else {
      throw new HttpException('退出失败', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  // 用户信息相关接口
  @Get('info')
  @ApiOperation({ summary: '获取当前登录用户信息' })
  async getUserInfo(@Request() request) {
    // 这里假设从请求中获取当前用户ID，具体实现要根据你的认证方式调整
    const userId = request.user?.id;
    if (!userId) {
      throw new HttpException('未登录', HttpStatus.UNAUTHORIZED);
    }
    return this.userAdminService.getUserInfo(userId);
  }

  @Get('userInfoById/:id')
  @ApiOperation({ summary: '获取用户详细信息' })
  async getUserById(@Param('id') id: number) {
    return await this.userAdminService.getUserById(id);
  }

  // 用户管理CRUD接口
  @Post()
  @Public()
  @ApiOperation({ summary: '创建用户' })
  create(@Body() createUserDto: CreateUserDto) {
    return this.userAdminService.create(createUserDto);
  }

  @Put(':id')
  @ApiOperation({ summary: '更新用户信息' })
  update(@Param('id') id: number, @Body() updateUserDto: UpdateUserDto) {
    return this.userAdminService.update(id, updateUserDto);
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除用户' })
  remove(@Param('id') id: number) {
    return this.userAdminService.remove(id);
  }
  
  @Get()
  @ApiOperation({ summary: '分页获取用户信息列表' })
  findAll(@Query() query: UserQueryDto) {
    return this.userAdminService.findAll(query);
  }
}